跳到主要内容

Action

1. 前言

本小节我们将介绍如何使用 Action。包括如何定义 Action、分发 Action、mapActions 辅助函数的使用方式。Action 在 Vuex 中会大量使用,学好如何使用 Action 非常重要。Action 并不是一个难点,它的使用非常简单,接下来我们就一步步学习它的使用。

2. Action 简介

Action 类似于 Mutation,不同的是:

    1. Action 提交的是 mutation,而不是直接变更状态。
    1. Action 可以包含任意异步操作。在 vuex 的使用过程中,我们可以将多个 Mutation 合并到一个 Action 中,也可以通过 Action 进行异步操作。

3. 基础用法

3.1 定义 action

Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
// 同步 action
increment (context) {
context.commit('increment')
},
// 异步 action
incrementAsync (context) {
setTimeout(() => {
context.commit('increment')
}, 1000)
}
}
})

实践中,我们会经常用到 ES2015 的参数解构来简化代码(特别是我们需要调用 commit 很多次的时候):

actions: {
increment ({ commit }) {
commit('increment')
}
}

3.2 分发 Action

Action 通过 store.dispatch 方法触发:

store.dispatch('increment')

3.3 提交载荷(Payload)

你可以向 store.dispatch 传入额外的参数,即 Actions 的 载荷(payload):

action: {
increment ({commit}, payload) {
// 具体 action 内容
}
}

store.dispatch('increment', {count: 10})

3.4 对象风格的提交方式

提交 action 的另一种方式是直接使用包含 type 属性的对象:

store.dispatch({
type: 'increment',
count: 10
})

当使用对象风格的提交方式,整个对象都作为载荷传给 action 函数,因此 handler 保持不变:

actions: {
increment ({commit}, payload) {
// 具体 action 内容
}
}

完整示例: